package com.example.kuaizu.utils;

import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

/**
 * 邮件推广工具类
 */
@Component
@Log4j2
public class EmailPromotionUtils {

    //生层对应的Message-ID-
    protected static String genMessageID(String mailFrom) {
        // 生成Message-ID:
        if (!mailFrom.contains("@")) {
            throw new IllegalArgumentException("Invalid email format: " + mailFrom);
        }
        String domain = mailFrom.split("@")[1];
        UUID uuid = UUID.randomUUID();
        return "<" + uuid.toString() + "@" + domain + ">";
    }

    //设置收件人地址
    private static void setRecipients(MimeMessage message, Message.RecipientType type, String[] recipients)
            throws MessagingException {
        // 设置收件人地址
        if (recipients == null || recipients.length == 0) {
            return; // 空列表不设置
        }
        InternetAddress[] addresses = new InternetAddress[recipients.length];
        for (int h = 0; h < recipients.length; h++) {
            addresses[h] = new InternetAddress(recipients[h]);
        }
        message.setRecipients(type, addresses);
    }

    //创建邮件会话
    private static MimeMessage createMailSession(Properties props, Authenticator authenticator,String userName) {
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        //mailSession.setDebug(true);// 开启 debug 模式，可以看到详细的发送 log
        String messageIDValue = genMessageID(userName);
        MimeMessage message = new MimeMessage(mailSession) {
            @Override
            protected void updateMessageID() throws MessagingException {
                setHeader("Message-ID", messageIDValue);
            }
        };
        return message;
    }


    /**
     * 邮件推广主方法
     * @param emailAdds 邮件地址数组
     * @param props 配置信息 springboot容器
     * @param authenticator 认证信息 springboot容器
     * @param userName 发件人邮箱地址 springboot容器
     */
    //发送邮件
    //@Bean
    public static Integer sendEmail(String[] emailAdds , Properties props, Authenticator authenticator, String userName , String emailText) {
        MimeMessage message = createMailSession(props, authenticator,userName);
        MimeMessage mimeMessage = prepareAndSendEmail(message, emailAdds,userName,emailText);
        if (mimeMessage != null) {
            try {
                Transport.send(message);
                return 1;
            } catch (MessagingException e) {
                log.error("邮件发送失败:{}", e.getMessage());
                //e.printStackTrace();
                return 2;
            }
            //return message;
        } else {
            log.error("邮件发送失败");
            return null;
        }
        //// 发送附件和内容：
        //// 创建多重消息
        //Multipart multipart = new MimeMultipart();
        //
        //// 创建一个 BodyPart 用于 HTML 内容
        //BodyPart htmlPart = new MimeBodyPart();
        //htmlPart.setContent("测试<br> html内容4", "text/html;charset=UTF-8");// 设置邮件的内容，会覆盖前面的 message.setContent
        //multipart.addBodyPart(htmlPart);
        //
        //// 添加完整消息
        //message.setContent(multipart);
    }

    //设置发送邮件前的内容准备
    private static MimeMessage prepareAndSendEmail(MimeMessage message, String[] emailAdds ,String userName,String emailText) {
        try {
            // 设置发件人邮件地址和名称。填写控制台配置的发信地址。和上面的 mail.user 保持一致。名称用户可以自定义填写。
            InternetAddress from = new InternetAddress(userName, "快组官方");// from 参数,可实现代发，注意：代发容易被收信方拒信或进入垃圾箱。
            message.setFrom(from);

            // setRecipients(message, Message.RecipientType.TO, new String[]{"sqdxqx@163.com", "收信地址2"});
            // setRecipients(message, Message.RecipientType.CC, new String[]{"sqdxqx@163.com", "收信地址4"});
            setRecipients(message, Message.RecipientType.BCC, emailAdds);

            // InternetAddress replyToAddress = new InternetAddress("回信地址");
            // message.setReplyTo(new Address[]{replyToAddress});// 可选。设置回信地址
            message.setSentDate(new Date());
            message.setSubject("组队邀请");//邮件标题
            message.setContent(emailText, "text/html;charset=UTF-8");// HTML 内容，若使用 MimeBodyPart 这里会被覆盖
            return message;
        } catch (MessagingException | UnsupportedEncodingException e) {
            System.err.println("邮件发送失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
        //return null;
    }

    //验证邮箱是否合法
    public static boolean isEmailValid(String email) {
        // 正则表达式模式
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        return email.matches(emailRegex);
    }


}
